package com.foreveross.taskservice.taskcache.redis;

import java.util.LinkedHashSet;
import java.util.Set;

import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import com.foreveross.taskservice.common.CacheDataSpace;
import com.foreveross.taskservice.common.model.AbstractTaskModel;
import com.foreveross.taskservice.taskcache.ITaskCacheFlush;
import com.foreveross.taskservice.taskcache.redis.core.TaskRedisCallback;
import com.google.common.collect.Sets;

/**
 * 实现清理部分
 * 
 * @author Administrator
 * 
 */
@Service
public class RedisTaskCacheFlushImpl extends BaseRedisTaskCache implements
		ITaskCacheFlush {
	@Override
	@Deprecated
	public Set<AbstractTaskModel> flushTask(final CacheDataSpace d, final String channelId)
			throws Exception {
		TaskRedisCallback<Set<AbstractTaskModel>> action=new TaskRedisCallback<Set<AbstractTaskModel>>() {
			
			@Override
			public Set<AbstractTaskModel> doInRedis(Jedis j) throws Exception {
				byte[] wKey=buildChannelWaitQueueKeyByte(d, channelId);
				byte[] dKey=buildChannelDoingQueueKeyByte(d, channelId);
				byte[] fKey=buildChannelFinishQueueKeyByte(d, channelId);
				byte[] pKey=buildChannelPauseQueueKeyByte(d, channelId);
				LinkedHashSet<byte[]> ids=Sets.newLinkedHashSet();
				ids.addAll(j.zrange(wKey, 0, -1));
				ids.addAll(j.zrange(dKey, 0, -1));
				ids.addAll(j.zrange(fKey, 0, -1));
				ids.addAll(j.zrange(pKey, 0, -1));
				LinkedHashSet<AbstractTaskModel>  models=findCacheTasks(ids, true, j);
				Pipeline pl=openPipeline(j, true);
				pl.del(wKey,dKey,fKey,pKey);//删除队列
				byte[] detailKey=buildHaskDetailKeyByte();
//				byte[][] idss=new byte[ids.size()][];
//				int i=0;
//				for(byte[] id:ids){
//					idss[i]=id;
//					i++;
//				}
//				pl.hdel(detailKey,idss);
				for(byte[] id:ids){
					pl.hdel(detailKey,id);
				}//删除任务
				syncPipline(pl, true);
				return models;
			}
		};
		return excuteDefaultLock(action, d, channelId);
	};
	

	public boolean flushDB() throws Exception {
		return getTaskRedisTemplate().execute(new TaskRedisCallback<Boolean>() {

			@Override
			public Boolean doInRedis(Jedis j) throws Exception {
				j.flushDB();
				return true;
			}
		});
	};

	//
	public boolean flushAll() throws Exception {
		return getTaskRedisTemplate().execute(new TaskRedisCallback<Boolean>() {

			@Override
			public Boolean doInRedis(Jedis j) throws Exception {
				j.flushAll();
				return true;
			}
		});
	}

	
}
